import React, { useState, useEffect } from 'react';
import {
    Badge,
    Popover,
    List,
    Avatar,
    Button,
    Divider,
    Tag,
    Empty,
    Spin
} from 'antd';
import {
    BellOutlined,
    MessageOutlined,
    NotificationOutlined,
    CloseOutlined,
    CheckCircleOutlined
} from '@ant-design/icons';

const primaryColor = '#1890ff';
const textColor = 'rgba(0, 0, 0, 0.85)';
const textColorSecondary = 'rgba(0, 0, 0, 0.45)';
const itemHoverBg = '#f5f5f5';

const MessageCenter = () => {
    const [loading, setLoading] = useState(false);
    const [messages, setMessages] = useState([]);
    const [unreadCount, setUnreadCount] = useState(0);

    useEffect(() => {
        setLoading(true);
        setTimeout(() => {
            setMessages([
                {
                    id: '1',
                    type: 'notification',
                    title: '系统升级通知',
                    content: '系统将于今晚24:00进行升级维护，预计耗时2小时。',
                    time: '2023-05-15 14:30',
                    read: false,
                    avatar: null
                },
                {
                    id: '2',
                    type: 'message',
                    title: '新消息',
                    content: '您提交的订单已经处理完成，请及时查看。',
                    time: '2023-05-15 10:15',
                    read: false,
                    avatar: 'https://randomuser.me/api/portraits/men/1.jpg'
                },
                {
                    id: '3',
                    type: 'alert',
                    title: '安全提醒',
                    content: '检测到您的账号在异地登录，如非本人操作请立即修改密码。',
                    time: '2023-05-14 18:45',
                    read: true,
                    avatar: null
                },
                {
                    id: '4',
                    type: 'message',
                    title: '新消息',
                    content: '您的退款申请已通过审核，款项将在3个工作日内退回。',
                    time: '2023-05-14 09:20',
                    read: true,
                    avatar: 'https://randomuser.me/api/portraits/women/2.jpg'
                }
            ]);
            setUnreadCount(2);
            setLoading(false);
        }, 800);
    }, []);

    const markAllAsRead = () => {
        setMessages(messages.map(msg => ({ ...msg, read: true })));
        setUnreadCount(0);
    };

    const markAsRead = (id) => {
        setMessages(messages.map(msg =>
            msg.id === id ? { ...msg, read: true } : msg
        ));
        setUnreadCount(prev => prev > 0 ? prev - 1 : 0);
    };

    const deleteMessage = (id) => {
        const message = messages.find(msg => msg.id === id);
        if (!message.read) {
            setUnreadCount(prev => prev > 0 ? prev - 1 : 0);
        }
        setMessages(messages.filter(msg => msg.id !== id));
    };

    const getMessageIcon = (type) => {
        switch (type) {
            case 'notification':
                return <NotificationOutlined style={{ color: '#1890ff' }} />;
            case 'message':
                return <MessageOutlined style={{ color: '#52c41a' }} />;
            case 'alert':
                return <NotificationOutlined style={{ color: '#f5222d' }} />;
            default:
                return <BellOutlined />;
        }
    };

    const content = (
        <div style={{ width: 350 }}>
            <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                padding: '12px 16px'
            }}>
                <h4 style={{ margin: 0, fontWeight: 500 }}>消息中心</h4>
                <Button
                    type="text"
                    size="small"
                    onClick={markAllAsRead}
                    disabled={unreadCount === 0}
                >
                    全部已读
                </Button>
            </div>
            <Divider style={{ margin: '8px 0' }} />

            {loading ? (
                <div style={{ display: 'flex', justifyContent: 'center', padding: '24px 0' }}>
                    <Spin />
                </div>
            ) : messages.length === 0 ? (
                <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description="暂无消息"
                />
            ) : (
                <List
                    itemLayout="horizontal"
                    dataSource={messages}
                    renderItem={(item) => (
                        <List.Item
                            style={{
                                padding: '12px 16px',
                                cursor: 'pointer',
                                backgroundColor: item.read ? 'transparent' : 'rgba(24,144,255,0.1)',
                                transition: 'all 0.3s'
                            }}
                            onMouseEnter={(e) => {
                                e.currentTarget.style.backgroundColor = item.read ? itemHoverBg : 'rgba(24,144,255,0.15)';
                            }}
                            onMouseLeave={(e) => {
                                e.currentTarget.style.backgroundColor = item.read ? 'transparent' : 'rgba(24,144,255,0.1)';
                            }}
                            actions={[
                                <Button
                                    type="text"
                                    icon={<CloseOutlined />}
                                    size="small"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        deleteMessage(item.id);
                                    }}
                                />,
                                !item.read && (
                                    <Button
                                        type="text"
                                        icon={<CheckCircleOutlined />}
                                        size="small"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            markAsRead(item.id);
                                        }}
                                    />
                                )
                            ].filter(Boolean)}
                        >
                            <List.Item.Meta
                                avatar={
                                    item.avatar ? (
                                        <Avatar src={item.avatar} />
                                    ) : (
                                        <Avatar icon={getMessageIcon(item.type)} />
                                    )
                                }
                                title={
                                    <div style={{
                                        display: 'flex',
                                        alignItems: 'center'
                                    }}>
                                        <span>{item.title}</span>
                                        <Tag
                                            color={item.type === 'alert' ? 'red' : 'blue'}
                                            style={{ marginLeft: 8 }}
                                        >
                                            {item.type === 'notification' ? '通知' :
                                                item.type === 'message' ? '消息' : '提醒'}
                                        </Tag>
                                        {!item.read && (
                                            <span style={{
                                                display: 'inline-block',
                                                width: 6,
                                                height: 6,
                                                borderRadius: '50%',
                                                backgroundColor: primaryColor,
                                                marginLeft: 8
                                            }} />
                                        )}
                                    </div>
                                }
                                description={
                                    <div>
                                        <div style={{
                                            color: textColor,
                                            whiteSpace: 'nowrap',
                                            overflow: 'hidden',
                                            textOverflow: 'ellipsis'
                                        }}>{item.content}</div>
                                        <div style={{
                                            color: textColorSecondary,
                                            fontSize: 12,
                                            marginTop: 4
                                        }}>{item.time}</div>
                                    </div>
                                }
                            />
                        </List.Item>
                    )}
                />
            )}
            <Divider style={{ margin: '8px 0' }} />
            <div style={{ textAlign: 'center', padding: '8px 0' }}>
                <Button type="link" size="small">查看全部消息</Button>
            </div>
        </div>
    );

    return (
        <div style={{ marginRight: 16 }}>
            <Popover
                placement="bottomRight"
                content={content}
                trigger="click"
            >
                <Badge count={unreadCount} overflowCount={99} size={'small'}  offset={[5, 15]}>
                    <Button
                        type="text"
                        icon={<BellOutlined style={{ fontSize: 18 }} />}
                        style={{
                            color: 'rgba(255, 255, 255, 0.65)',
                            fontSize: 16,
                            padding: '0 12px',
                            height: 64
                        }}
                        onMouseEnter={(e) => e.currentTarget.style.color = primaryColor}
                        onMouseLeave={(e) => e.currentTarget.style.color = 'rgba(255, 255, 255, 0.65)'}
                    />
                </Badge>
            </Popover>
        </div>
    );
};

export default MessageCenter;
